package com.cy.redis;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@SpringBootTest
public class RedisTemplateTest2 {

    /**
     * RedisTemplate用于操作复杂的数据结构，例如hash。。。
     * */
    @Autowired
    private RedisTemplate redisTemplate;

    //通过方法直接flushall清理redis的缓存数据，慎用会导致缓存雪崩
    @Test
    void redisFlushDb() {

        redisTemplate.execute(new RedisCallback() {
            @Override
            public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {

                redisConnection.flushAll();
                return null;
            }
        });

    }


    @Test
    void testSet() {

        SetOperations setOperations = redisTemplate.opsForSet();
        setOperations.add("set1", "A","B","C");
        setOperations.add("set1", "A","D","C");
        Long set1 = setOperations.size("set1");
        System.out.println(set1);

    }


    @Test
    void testList() {

        ListOperations opsForList = redisTemplate.opsForList();
        opsForList.leftPush("A", 100);
        opsForList.leftPush("A", 200);
        opsForList.leftPush("A", 300);
        Object a = opsForList.rightPop("A");
        System.out.println(opsForList.range("A", 0, -1));
        //测试阻塞式队列,每次执行时需要在redis中flushdb
        opsForList.rightPop("A");
        opsForList.rightPop("A");
        Object a1 = opsForList.rightPop("A", 10, TimeUnit.SECONDS);
        System.out.println(a1);

    }


    @Test
    void testHashOper() {

        HashOperations hashOperations = redisTemplate.opsForHash();

        HashMap<Object, Object> map = new HashMap<>();
        map.put("mobile", "188");
        map.put("email","188@qq.com");
        hashOperations.putAll("member", map);

        //putIfAbsent往对象放入数据时，假如key已经存在，那么后续放入这个key时不能继续存入
        hashOperations.putIfAbsent("member", "sex", "men");
        hashOperations.putIfAbsent("member", "sex", "women");


        hashOperations.put("member", "id",101 );
        hashOperations.put("member", "name", "杜兰特");
        //这里放入相同key时，对应value会被覆盖
        hashOperations.put("member", "name", "欧文");
        Object id = hashOperations.get("member", "id");
        Object name = hashOperations.get("member", "name");
        System.out.println("get redis hash= " + id + name);

        Map entries = hashOperations.entries("member");
        System.out.println(entries);

    }

}
